package com.ustadzmenjawab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.InputType;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.UnderlineSpan;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
public class UstadzMenjawabActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	//private Activity mainAct = null;
	private String curr_keyword = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		setContentView(R.layout.main);
		Button button = (Button)findViewById(R.id.button1);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);

		button.setOnClickListener(this);
		//mainAct = this;
	}

	@Override
	public void onClick(View view) {

		if(R.id.button1 == view.getId()){
			final EditText searchBox = (EditText) findViewById(R.id.editText1);
			if(searchBox.getText().length() > 0){
				new SearchKeywordTask(this).execute(searchBox.getText().toString());
			}else{
				//Pop up warning for empty search keyword here.
				AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
				alertbox.setMessage("Mohon masukkan kata pencarian."); 
				alertbox.setNeutralButton(R.string.OK, new DialogInterface.OnClickListener() {
					// click listener on the alert box
					public void onClick(DialogInterface arg0, int arg1) {
						// the button was clicked
						searchBox.requestFocus();
					}
				});
				// show it
				alertbox.show();
			}
		}else{
			TextView pageLink = (TextView) view;
			String startstr = pageLink.getText().toString();
			int start = (Integer.parseInt(startstr) - 1) * Integer.parseInt(getResources().getString(R.string.hit_per_page));
			new SearchKeywordTask(this).execute(getCurrKeyword(),""+start);
		}
	}

	public static InputStream getInputStreamFromUrl(String url) {
		InputStream content = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpClient httpclient = new DefaultHttpClient();
			// Execute HTTP Get Request
			HttpResponse response = httpclient.execute(httpGet);
			if(response != null)
				content = response.getEntity().getContent();
		} catch (Exception e) {
			//handle the exception !
			e.printStackTrace();
		}
		return content;
	}

	public static String covertStreamToString(InputStream is){
		BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
		String line;
		StringBuilder sb =  new StringBuilder();
		try {
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}

			rd.close();
			String contentOfMyInputStream = sb.toString();
			return contentOfMyInputStream;
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null;
	}
	private void setCurrKeyword(String keyword){
		this.curr_keyword = keyword;
	}
	public String getCurrKeyword(){
		return this.curr_keyword;
	}
	class SearchKeywordTask extends AsyncTask<String, Integer, JSONObject>{
		Resources resource = null;
		UstadzMenjawabActivity mainAct = null;
		String keyword = null;
		public SearchKeywordTask(UstadzMenjawabActivity parent){
			resource = parent.getResources();
			mainAct = parent;
			
		}
		
		@Override
		protected void onPreExecute (){
			final TableLayout epView = (TableLayout) mainAct.findViewById(R.id.tableLayout1);
			epView.removeAllViews();
			LinearLayout linProgressBar = (LinearLayout) findViewById(R.id.lin_progress_bar);
			linProgressBar.setVisibility(View.VISIBLE);
		}
		@Override
		protected JSONObject doInBackground(String... args) {
			try {
				String encodedKeyword = URIUtil.encodeQuery(args[0]);
				this.keyword = args[0];
				int start = 0;
				if(args.length > 1 && args[1] != null)
					start = Integer.parseInt(args[1]);
				mainAct.setCurrKeyword(this.keyword);
				InputStream response = getInputStreamFromUrl(resource.getString(R.string.search_url)+"?keyword="+encodedKeyword+"&start="+start+"&device_type=Android");
				if(response != null){
					String jsonStr = covertStreamToString(response);
					if(jsonStr != null && jsonStr.length() >0){
						JSONObject jsonObject = new JSONObject(jsonStr);
						return jsonObject;
					}
					return null;
				}
				return null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onProgressUpdate(Integer... progress) {
			//  setProgressPercent(progress[0]);
		}
		@Override
		protected void onPostExecute(JSONObject jsonObject) {
			if(jsonObject == null){
				//No result found;
				return;
			}
			String totalCntStr;
			try {
				totalCntStr = jsonObject.getString("total_count");

				int totalCnt = Integer.parseInt(totalCntStr);
				
				ScrollView sv  = (ScrollView)findViewById(R.id.scrollView1);
				sv.fullScroll(ScrollView.FOCUS_UP);
				if(totalCnt > 0){
					JSONArray results = jsonObject.getJSONArray("results");
					int hitPerPage = Integer.parseInt(resource.getString(R.string.hit_per_page));
					int numPage = 1;
					if(totalCnt < hitPerPage){
						hitPerPage = totalCnt;
					}else{
						if(totalCnt > 50)
							numPage = 5;
						else{
							numPage = (int)Math.ceil(((double)totalCnt) / hitPerPage);
						}
					}
					final TableLayout epView = (TableLayout) mainAct.findViewById(R.id.tableLayout1);
					for(int i = 0; i < hitPerPage; i++){
						JSONObject rec = results.getJSONObject(i);

						/* Create a new row for title. */
						TableRow title = new TableRow(mainAct);
						title.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						TextView t3 = new TextView(mainAct);
						t3.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
						t3.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
						t3.setSingleLine(false);
						t3.setMaxLines(3);
						t3.setTextColor(R.color.blue);
						String qtitle = rec.getString("judul");
						qtitle = qtitle.substring(0,1).toUpperCase() + qtitle.substring(1).toLowerCase();	 
						t3.setText(Html.fromHtml("<a href=\""+rec.getString("url")+"\">"+qtitle+"</a> "));
						t3.setMovementMethod(LinkMovementMethod.getInstance());
						title.addView(t3);

						/*Create a new row for summary*/
						TableRow summary = new TableRow(mainAct);
						summary.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						TextView t4 = new TextView(mainAct);
						t4.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
						t4.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
						t4.setSingleLine(false);
						t4.setMaxLines(5);
						t4.setTextColor(R.color.black);
						String summaryTxt = rec.getString("summary").toLowerCase();
						//  summaryTxt = summaryTxt.substring(0, summaryTxt.lastIndexOf("..."));
						t4.setText(Html.fromHtml(summaryTxt));

						summary.addView(t4);

						/*Create a new row for source*/
						TableRow source = new TableRow(mainAct);
						source.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						TextView t5 = new TextView(mainAct);
						t5.setText(Html.fromHtml("<font color=\"green\">"+rec.getString("sumber")+"</font>"));
						t5.setMovementMethod(LinkMovementMethod.getInstance());
						source.addView(t5);

						/*Create an empty row*/
						TableRow empty = new TableRow(mainAct);
						empty.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						TextView t6 = new TextView(mainAct);
						t6.setText(Html.fromHtml("&nbsp;"));
						empty.addView(t6);

						/* Add row to TableLayout. */
						epView.addView(title,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						epView.addView(summary,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						epView.addView(source,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
						epView.addView(empty,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
					}
					/*Create a new row for source*/
					TableRow paging = new TableRow(mainAct);
					paging.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
					paging.setGravity(Gravity.CENTER_HORIZONTAL);
					
					TableLayout pageTbl = new TableLayout(mainAct);
					Display display = getWindowManager().getDefaultDisplay(); 
					int scrwidth = display.getWidth();
					
					//String pageURL = "";
					for(int p = 1 ; p <= numPage; p++){
						//pageURL +="<a href=\""+resource.getString(R.string.search_url)+"?keyword="+keyword+"&start="+p*hitPerPage+"&device_type=Android"+"\">"+p+"</a>";
						//pageURL +="&nbsp;&nbsp;&nbsp;";
						TextView t6 = new TextView(mainAct);
						t6.setTextColor(resource.getColor(R.color.blue));
						t6.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
						SpannableString content = new SpannableString(""+p);
						content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
						t6.setText(content);
						t6.setWidth(scrwidth/15);
						t6.setOnClickListener(mainAct);
						t6.setMovementMethod(LinkMovementMethod.getInstance());
						t6.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
						paging.addView(t6);
					}
					//t6.setText(Html.fromHtml(pageURL));
					
					pageTbl.addView(paging,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
					pageTbl.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
					epView.addView(pageTbl, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
					LinearLayout linProgressBar = (LinearLayout) findViewById(R.id.lin_progress_bar);
					linProgressBar.setVisibility(View.GONE);
				}else{
					//No search result found.
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
	}

}